<template>
  <view class="transfer-add-container">
    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 转移单号 -->
      <view class="form-item">
        <view class="item-label required">转移单号</view>
        <view class="item-value readonly">{{ isEdit ? formData.transferCode : '系统自动生成' }}</view>
      </view>
      
      <!-- 转移单名称 -->
      <view class="form-item">
        <view class="item-label">转移单名称</view>
        <input class="item-input" type="text" v-model="formData.transferName" placeholder="请输入转移单名称" />
      </view>
      
      <!-- 转移人 -->
      <view class="form-item" @click="showTransferUserPicker = true">
        <view class="item-label required">转移人</view>
        <view class="item-value picker">
          <text>{{ formData.transferUserName || '请选择' }}</text>
          <u-icon name="arrow-right" size="28rpx" color="#999"></u-icon>
        </view>
      </view>
      
      <!-- 接收人 -->
      <view class="form-item" @click="showreceiverUserPicker = true">
        <view class="item-label required">接收人</view>
        <view class="item-value picker">
          <text>{{ formData.receiverUserName || '请选择' }}</text>
          <u-icon name="arrow-right" size="28rpx" color="#999"></u-icon>
        </view>
      </view>

      <!-- 接收位置 -->
      <view class="form-item" @click="showLocationPicker = true">
        <view class="item-label required">接收位置</view>
        <view class="item-value picker">
          <text>{{ formData.receiverLocationName || '请选择' }}</text>
          <u-icon name="arrow-right" size="28rpx" color="#999"></u-icon>
        </view>
      </view>

      <!-- 接收管理员 -->
      <view class="form-item" @click="showManagerPicker = true">
        <view class="item-label required">接收管理员</view>
        <view class="item-value picker">
          <text>{{ formData.receiverAdminName || '请选择' }}</text>
          <u-icon name="arrow-right" size="28rpx" color="#999"></u-icon>
        </view>
      </view>

      <!-- 转移日期 -->
      <view class="form-item">
        <view class="item-label required">转移日期</view>
        <view class="item-value picker" @click="showTransferDate = true">
          <text>{{ formData.transferDate || '请选择' }}</text>
          <u-icon name="arrow-right" size="28rpx" color="#999"></u-icon>
        </view>
      </view>

      <!-- 备注 -->
      <view class="form-item">
        <view class="item-label">备注</view>
	  	<view class="item-value picker">
	  		<u-input v-model="formData.remark" placeholder="请输入备注信息" border="none" />
		</view>
      </view>
    </view>
    
    <!-- 资产列表 -->
    <view class="assets-section">
      <view class="section-header">
        <view class="section-title">资产列表</view>
        <view class="section-count">共计: {{ selectedAssets.length }}</view>
      </view>
      
      <!-- 资产列表内容 -->
      <view class="assets-list">
        <template v-if="selectedAssets.length > 0">
          <view class="asset-item" v-for="(item, index) in selectedAssets" :key="index">
            <view class="asset-image">
              <image :src="item.image ? `${BASE_URL}/File/GetImage?fileId=${item.image}` : '/static/placeholder.png'" mode="aspectFill"></image>
            </view>
            <view class="asset-info">
              <view class="asset-name">{{ item.assetName }}</view>
              <view class="asset-detail">资产分类: {{ item.assetClassName }}</view>
              <view class="asset-detail">资产编码: {{ item.assetCode }}</view>
              <view class="asset-detail">规格型号: {{ item.specModel }}</view>
            </view>
            <view class="asset-action">
              <u-icon name="close" size="40rpx" color="#999" @click="removeAsset(index)"></u-icon>
            </view>
          </view>
        </template>
        <view class="empty-assets" v-else>
          <u-empty mode="data" text="暂无资产，请点击下方添加按钮添加资产"></u-empty>
        </view>
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="footer-buttons">
      <view class="btn-add" @click="goToSelectAssets">添加</view>
      <view class="btn-submit" @click="submitForm">提交</view>
    </view>
    
    <!-- 转移人选择器 -->
    <up-picker
      :show="showTransferUserPicker"
      :columns="[userList]"
      keyName="text"
      @cancel="showTransferUserPicker = false"
      @confirm="confirmTransferUser"
      :closeOnClickOverlay="false"
    />
    
    <!-- 接收人选择器 -->
    <up-picker
      :show="showreceiverUserPicker"
      :columns="[userList]"
      keyName="text"
      @cancel="showreceiverUserPicker = false"
      @confirm="confirmreceiverUser"
      :closeOnClickOverlay="false"
    />

    <!-- 接收位置选择器 -->
    <up-picker
      :show="showLocationPicker"
      :columns="[locationList]"
      keyName="text"
      @cancel="showLocationPicker = false"
      @confirm="confirmLocation"
      :closeOnClickOverlay="false"
    />
	    <!-- 接收管理员选择器 -->
	<up-picker
      :show="showManagerPicker"
      :columns="[userList]"
      keyName="text"
      @cancel="showManagerPicker = false"
      @confirm="confirmManager"
      :closeOnClickOverlay="false"
    />
	    <!-- 日期选择器 -->
	<up-datetime-picker
      :show="showTransferDate"
      mode="date"
      v-model="dateTime"
      closeOnClickOverlay
      @confirm="confirmTransferDate"
      @cancel="showTransferDate = false"
      @close="showTransferDate = false"
    ></up-datetime-picker>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import http, { BASE_URL } from "@/api/request";
import { generateUUID ,formatTimestamp} from '@/utils';
import { t } from "@/locale/index.js"

// 是否是编辑模式
const isEdit = ref(false);

// 表单数据
const formData = ref({
  id: '',
  transferCode: '系统自动生成',
  transferName: '',
  transferUser: '',
  transferUserName: '',
  receiverUser: '',
  receiverUserName: '',
  receiverLocation: '',
  receiverLocationName: '',
  receiverAdmin: '',      // 新增：接收管理员ID
  receiverAdminName: '',  // 新增：接收管理员名称
  transferDate: '',        // 新增：转移日期
  remark: ''              // 新增：备注
});

// 选择的资产列表
const selectedAssets = ref([]);

// 选择器状态
const showTransferUserPicker = ref(false);
const showreceiverUserPicker = ref(false);
const showLocationPicker = ref(false);
// 选择器状态
const showManagerPicker = ref(false);    // 新增：接收管理员选择器状态
const showTransferDate = ref(false);     // 新增：转移日期选择器状态

// 选择器数据
const userList = ref([]);
const locationList = ref([]);
const pageParams = ref({
  transferCode: '',
  mode: ''
});

// 初始化为当前日期
const dateTime = ref(Date.now());

// 页面加载时判断是否为编辑模式
onLoad((options) => {
  // 保存页面参数
  pageParams.value = {
    transferCode: options.transferCode || '',
    mode: options.mode || ''
  };

  // 判断是否为编辑模式
  if(pageParams && pageParams.value.transferCode){
    isEdit.value = true;
    formData.value.transferCode = options.transferCode;
    // 加载转移单详情
    loadTransferDetail(options.transferCode);
    uni.setNavigationBarTitle({
      title: t("assetTransfer.edit")
    });
  }else{
    uni.setNavigationBarTitle({
      title: t("assetTransfer.add")
    });
  }

  // 加载用户列表
  loadUserList();
  
  // 加载位置列表
  loadLocationList();

});

// 加载转移单详情
const loadTransferDetail = (transferCode) => {
  uni.showLoading({
    title: '加载中...'
  });
  
  http.post('/api/module/Invoke', {
    pageCode: 'assettransfer',
    params: {
      args: [
        {
          name: 'interfaceCode',
          value: 'assettransfer.getAssetTransferOrderDetail'
        },
        {
          name: 'transferCode',
          value: transferCode
        }
      ]
    },
    methodName: 'getAssetTransferOrderDetail'
  }).then(res => {
    uni.hideLoading();
    
    if (res.isSuccess && res.result) {
      const { masterInfo, assetDetails } = res.result;
      
      // 填充表单数据
      formData.value = {
        id: masterInfo.id,
        transferCode: masterInfo.transferCode,
        transferName: masterInfo.transferName,
        transferUser: masterInfo.transferUser,
        transferUserName: masterInfo.transferUserName,
        receiverUser: masterInfo.receiverUser,
        receiverUserName: masterInfo.receiverUserName,
        receiverLocation: masterInfo.receiverLocation,
        receiverLocationName: masterInfo.receiverLocationName,
        receiverAdmin: masterInfo.receiverAdmin,
        receiverAdminName: masterInfo.receiverAdminName,
        transferDate: masterInfo.fTransferDate || '',
        remark: masterInfo.remark || '',
        transferState: masterInfo.transferState,
      };
      
      // 填充资产列表
      if (assetDetails && Array.isArray(assetDetails)) {
        selectedAssets.value = assetDetails.map(item => ({
          id: item.id,
          assetId: item.id,
          assetCode: item.assetCode,
          assetName: item.assetName,
          assetClassName: item.assetClassName,
          specModel: item.specModel,
          image: item.image
        }));
      }
    } else {
      uni.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    console.error('加载转移单详情失败:', err);
    uni.hideLoading();
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    });
  });
};

// 页面显示
onShow(() => {
  // 检查是否有从资产选择页面返回的数据
  uni.$once('assetSelected', (assets) => {
    handleSelectAssets(assets);
  });
});

// 加载用户列表
const loadUserList = () => {
  const data = {
    code: "Sys_GetUserNameById",
    filters: [],
    allColumnFilter: true,
    tableFilters: []
  };

  http.post("/api/module/GetViewTable", data).then((res) => {
    if (res.isSuccess && res.result && res.result.viewTable) {
      userList.value = res.result.viewTable.map(item => ({
        text: item.text,
        value: item.id
      }));
    }
  }).catch(err => {
    console.error('获取用户列表失败:', err);
    uni.showToast({
      title: '获取用户列表失败',
      icon: 'none'
    });
  });
};

// 加载位置列表
const loadLocationList = () => {
  const params = [{
    id: generateUUID(),
    service: "Module",
    method: "getViewTable",
    param: JSON.stringify({
      code: "getAssetAddressList",
      filters: []
    })
  }];

  http.post("/api/module/GetBatchResult", params).then((res) => {
    if (res.isSuccess && res.code && res.result) {
      const locationData = res.result[0].response.data.viewTable || [];
      locationList.value = locationData.map(item => ({
        text: item.asset_address_name,
        value: item.asset_address_code
      }));
    } else {
      console.error('获取位置列表失败:', res.error);
      uni.showToast({
        title: '获取位置列表失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    console.error('获取位置列表失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
};

// 确认转移人选择
const confirmTransferUser = (e) => {
  const selectedUser = e.value[0];
  formData.value.transferUser = selectedUser.value;
  formData.value.transferUserName = selectedUser.text;
  showTransferUserPicker.value = false;
};

// 确认接收人选择
const confirmreceiverUser = (e) => {
  const selectedUser = e.value[0];
  formData.value.receiverUser = selectedUser.value;
  formData.value.receiverUserName = selectedUser.text;
  showreceiverUserPicker.value = false;
};

// 确认位置选择
const confirmLocation = (e) => {
  const selectedLocation = e.value[0];
  formData.value.receiverLocation = selectedLocation.value;
  formData.value.receiverLocationName = selectedLocation.text;
  showLocationPicker.value = false;
};

// 跳转到选择资产页面
const goToSelectAssets = () => {
  uni.navigateTo({
    url: '/components/assetsAddList/index?type=transfer'
  });
};

// 处理选择资产页面返回的数据
const handleSelectAssets = (assets) => {
  console.log('选择的资产:', assets);
  if (Array.isArray(assets) && assets.length > 0) {
    if (!selectedAssets.value) selectedAssets.value = [];
    
    // 转换资产数据格式
    const formattedAssets = assets.map(asset => ({
      id: asset.id,
      assetId: asset.id,
      assetName: asset.asset_name,
      assetClassName: asset.asset_category,
      assetCode: asset.asset_code,
      specModel: asset.spec_model,
      image: asset.image ? asset.image.trim() : '/static/images/default-asset.png'
    }));
    
    // 合并选中的资产，避免重复
    const existingIds = selectedAssets.value.map(item => item.id);
    const newAssets = formattedAssets.filter(asset => !existingIds.includes(asset.id));

    selectedAssets.value = [...selectedAssets.value, ...newAssets];
  }
};

// 移除资产
const removeAsset = (index) => {
  selectedAssets.value.splice(index, 1);
};

// 确认接收管理员选择
const confirmManager = (e) => {
  const selectedUser = e.value[0];
  formData.value.receiverAdmin = selectedUser.value;
  formData.value.receiverAdminName = selectedUser.text;
  showManagerPicker.value = false;
};

// 确认转移日期选择
const confirmTransferDate = (e) => {
  // 处理日期值，确保它是有效的
  let timestamp;
  
  // 处理不同格式的日期返回值
  if (typeof e === 'object') {
    if (e.value !== undefined) {
      timestamp = e.value; // 处理 {value: timestamp, mode: 'date'} 格式
    } else if (e.result !== undefined) {
      timestamp = e.result; // 处理 {result: timestamp} 格式
    } else {
      timestamp = Date.now(); // 默认使用当前时间
    }
  } else {
    timestamp = e; // 直接使用传入的值
  }
  
  // 使用时间戳创建日期对象
  const date = new Date(timestamp);
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    console.error('无效的日期值:', e);
    uni.showToast({
      title: '日期选择错误',
      icon: 'none'
    });
    return;
  }
    // 只保留年月日部分
	const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  formData.value.transferDate = `${year}-${month}-${day}`;
  
  showTransferDate.value = false;
};


// 提交表单
const submitForm = () => {
  // 表单验证
  if (!formData.value.transferUser) {
    uni.showToast({
      title: '请选择转移人',
      icon: 'none'
    });
    return;
  }
  
  if (!formData.value.receiverUser) {
    uni.showToast({
      title: '请选择接收人',
      icon: 'none'
    });
    return;
  }

  if (!formData.value.receiverLocation) {
    uni.showToast({
      title: '请选择接收位置',
      icon: 'none'
    });
    return;
  }

  if (!formData.value.receiverAdmin) {  // 新增：接收管理员验证
    uni.showToast({
      title: '请选择接收管理员',
      icon: 'none'
    });
    return;
  }

  if (!formData.value.transferDate) {    // 新增：转移日期验证
    uni.showToast({
      title: '请选择转移日期',
      icon: 'none'
    });
    return;
  }
  
  if (selectedAssets.value.length === 0) {
    uni.showToast({
      title: '请添加转移资产',
      icon: 'none'
    });
    return;
  }
  
  // 显示加载中
  uni.showLoading({
    title: '提交中...'
  });

  // 构建DTO对象
  const assetTransferSaveDTO = {
    id : formData.value.id || '',
    transfer_code : formData.value.transferCode || '',
    transfer_name: formData.value.transferName || '',
    transfer_user: formData.value.transferUser,
    receiver_user: formData.value.receiverUser,
    receiver_location: formData.value.receiverLocation,
    receiver_admin: formData.value.receiverAdmin,  // 新增：接收管理员
    transfer_date: formData.value.transferDate,      // 新增：转移日期
    remark: formData.value.remark || '',
    transfer_state: formData.value.transferState,
    transfer_dets: selectedAssets.value.map(asset => ({
      asset_code: asset.assetCode
    }))
  };

  // 调用保存接口
  http.post('/api/module/Invoke', {
    pageCode: 'assettransfer',
    params: {
      args: [
        {
          name: 'interfaceCode',
          value: 'assettransfer.saveAssetTransferOrder'
        },
        {
          name: 'dto',
          value: JSON.stringify(assetTransferSaveDTO)
        }
      ]
    },
    methodName: 'saveAssetTransferOrder'
  }).then(res => {
    uni.hideLoading();
    if (res.isSuccess) {
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      });
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.error || '保存失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    console.error('保存转移单失败:', err);
    uni.hideLoading();
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    });
  });
};
</script>

<style lang="scss">
.transfer-add-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;

  .form-section {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 12rpx;
    padding: 0 30rpx;

    .form-item {
      display: flex;
      align-items: center;
      min-height: 88rpx;
      border-bottom: 1rpx solid #eee;

      &:last-child {
        border-bottom: none;
      }

      .item-label {
        width: 180rpx;
        font-size: 28rpx;
        color: #333;

        &.required::before {
          content: '*';
          color: #ff4d4f;
          margin-right: 4rpx;
        }
      }

      .item-value {
        flex: 1;
        font-size: 28rpx;
        color: #666;

        &.readonly {
          color: #999;
        }

        &.picker {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
      }

      .item-input {
        flex: 1;
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  .assets-section {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 12rpx;
    padding: 30rpx;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .section-title {
        font-size: 30rpx;
        color: #333;
        font-weight: 500;
      }

      .section-count {
        font-size: 26rpx;
        color: #666;
      }
    }

    .assets-list {
      .asset-item {
        display: flex;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #eee;

        &:last-child {
          border-bottom: none;
        }

        .asset-image {
          width: 120rpx;
          height: 120rpx;
          margin-right: 20rpx;

          image {
            width: 100%;
            height: 100%;
            border-radius: 8rpx;
          }
        }

        .asset-info {
          flex: 1;

          .asset-name {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 8rpx;
          }

          .asset-detail {
            font-size: 24rpx;
            color: #666;
            margin-top: 4rpx;
          }
        }

        .asset-action {
          display: flex;
          align-items: center;
          padding: 0 10rpx;
        }
      }

      .empty-assets {
        padding: 60rpx 0;
      }
    }
  }

  .footer-buttons {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    padding: 20rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    .btn-add,
    .btn-submit {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 28rpx;
      color: #fff;
      border-radius: 40rpx;
      margin: 0 10rpx;
    }

    .btn-add {
      background-color: #ff9900;
    }

    .btn-submit {
      background-color: #2979ff;
    }
  }
}
</style>
